"""
model name : 深度学习
file       : iou.py
information:
    author : OuYang
    time   : 2025/1/18
"""
import torch


def iou_from_xyxy(boxes1, boxes2):
    """
    计算IOU
    :param boxes1: [(x1, y1), (x2, y2)]
    :param boxes2: [(x1, y1), (x2, y2)]
    :return: iou
    """

    b1_x1, b1_y1 = boxes1[0]
    b1_x2, b1_y2 = boxes1[1]

    b2_x1, b2_y1 = boxes2[0]
    b2_x2, b2_y2 = boxes2[1]

    inter_x1 = torch.max(b1_x1, b2_x1)
    inter_y1 = torch.max(b1_y1, b2_y1)
    inter_x2 = torch.min(b1_x2, b2_x2)
    inter_y2 = torch.min(b1_y2, b2_y2)

    b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
    b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
    inter_area = (inter_x2 - inter_x1) * (inter_y2 - inter_y1)

    union_area = b1_area + b2_area - inter_area
    return inter_area / torch.clamp(union_area)
